package com.jinhuhang.u2.myselfmodule.engine.user.login;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.AppCompatButton;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.common.mvp.fragment.ZSimpleBaseFragment;
import com.jinhuhang.u2.entity.UserBean;
import com.jinhuhang.u2.homemodule.GestureActivity;
import com.jinhuhang.u2.myselfmodule.engine.user.UserActivity;
import com.jinhuhang.u2.myselfmodule.engine.user.forget.ForgetActivity;
import com.jinhuhang.u2.ui.MainActivity;
import com.jinhuhang.u2.ui.customview.MyDialog;
import com.jinhuhang.u2.util.U2MD5Util;
import com.jinhuhang.u2.util.UtilsCollection;
import com.jinhuhang.u2.util.http.HttpWrapper;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.jinhuhang.u2.util.logger.Logger;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by OnionMac on 17/9/15.
 */

@SuppressLint("ValidFragment")
public class LoginFragment extends ZSimpleBaseFragment implements LoginContract.View {


    private static final int SETUP_GESTURE = 99;
    private static final int SETUP_GESTURE_RESULT = 100;

    @Bind(R.id.login_logo)
    ImageView mLoginLogo;
    @Bind(R.id.login_phone)
    EditText mLoginPhone;
    @Bind(R.id.login_password)
    EditText mLoginPassword;
    @Bind(R.id.tv_register_send)
    TextView mTvRegisterSend;
    @Bind(R.id.btn_register)
    AppCompatButton mBtnRegister;
    @Bind(R.id.login_toregister)
    TextView mLoginToregister;
    private UserActivity mUserActivity;

    private LoginContract.Presenter mPresenter;

    String setType;

    public LoginFragment(String type) {
        setType = type;
    }

    @Override
    protected void initView(View view) {
        mUserActivity = (UserActivity) getActivity();
    }

    private String phone;
    private String password;
    @Override
    protected void initListener() {
        mLoginToregister.setOnClickListener(v -> {
            mLoginPhone.setText("");
            mLoginPassword.setText("");
            mUserActivity.goRegister();
        });
        mBtnRegister.setOnClickListener(v -> {
            phone = mLoginPhone.getText().toString();
            password = mLoginPassword.getText().toString();

            if (!UtilsCollection.isMobileExact(phone)) {
                showMessage(getString(R.string.entercorrectphone));
                return;
            }

            if (TextUtils.isEmpty(password)) {
                showMessage("密码不能为空!");
                return;
            }

//            password = U2MD5Util.encryption(password);
            Map<String, String> map = new HashMap<>();
            map.put("username", phone);
            map.put("userId", Constant.DEFAULT_USER_ID);
            map.put("password", password);
            map.put("loginType", Constant.PLATFORM);
            mPresenter.Login(map);
        });

        mTvRegisterSend.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), ForgetActivity.class);
            intent.putExtra(ForgetActivity.FORGET_TYPE, ForgetActivity.FORGET_TYPE_LOGIN);
            startActivity(intent);
        });
    }

    @Override
    public void onResultLogin(HttpWrapper<UserBean> data) {
        if (Constant.SUCCESS_CODE == data.code) {
            /**
             * TODO  保存User数据
             */
            UserBean userBean = data.data;
            userBean.setUserName(phone);
            userBean.setLoginPwd(password);
            setUser(userBean);
            MainActivity.uid = userBean.getUserId();
            Logger.i(new Gson().toJson(getUser()));
            Intent intent = new Intent(getActivity(), GestureActivity.class);
            intent.putExtra(GestureActivity.TYPE, setType);
            startActivity(intent);
            getActivity().finish();
        } else if (Constant.ERROR_201 == data.code) {
            /**
             * 清空密码框
             */
            mLoginPassword.setText("");

       //     String str="账户或密码输入错误\n你还有<span style=\"color:#ff9966;\">"+4+"</span>尝试机会";
            MyDialog.showLoginDialog(data.getInfo(),getActivity());
//            UtilsCollection.getSingleDialog(getActivity(), "提 示", "用户名/密码输入有误,请重新输入", "确定", () -> {
//            }).show();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_login;
    }

    @Override
    protected void attachPre() {
        mPresenter = new LoginPresenter(this, getCompositeSubscription());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SETUP_GESTURE && resultCode == SETUP_GESTURE_RESULT) {
            startActivity(new Intent(mUserActivity, MainActivity.class));
            mUserActivity.finish();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mUserActivity.chargePre("1");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
